package com.dc.seckill.exception;

import com.dc.seckill.result.CodeMsg;
import com.dc.seckill.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @模块 异常处理模块
 * @作者 djs
 * @时间 2018/3/19 9:23
 * @版本 V1.0
 * @描述 对异常进行全局处理
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    public Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 异常处理
     * @params [request, e]
     * @returns com.dc.seckill.result.Result<java.lang.String>
     */
    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request, Exception e){

        if(e instanceof GlobalException){
            GlobalException ex = (GlobalException) e;
            return Result.error(ex.getCm());
        }else if (e instanceof BindException){
            BindException ex = (BindException)e;
            List<ObjectError> errors = ex.getAllErrors();
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            e.printStackTrace();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
        }else{
            e.printStackTrace();
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }

}
